package cn.vivi.seckill.controller;


import cn.vivi.seckill.anno.AccessLimit;
import cn.vivi.seckill.service.SecKillService;
import cn.vivi.seckill.vo.RespBean;
import cn.vivi.seckill.vo.RespBeanEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/seckill")
public class SecKillController {

    @Autowired
    private SecKillService secKillService;

    @GetMapping("/{path}/toSecKill/{id}")
    public RespBean toSecKill(@PathVariable String path,
                              @PathVariable("id") String goodsId,
                              @CookieValue String userTicket) {
        // 验证路径是否合法
        boolean isLegal = secKillService.checkPath(path, userTicket, goodsId);
        if (!isLegal) {
            return RespBean.error(RespBeanEnum.PATH_ILLEGAL);
        }
        return secKillService.isToSecKill(goodsId, userTicket);
    }

    /**
     * 获取秒杀结果
     * 返回订单id:秒杀成功
     * 返回 -1 秒杀失败
     * 返回 0 排队中
     */
    @GetMapping("/result/{id}")
    public RespBean getResult(@PathVariable("id") String goodsId, @CookieValue String userTicket) {
       return secKillService.getResult(goodsId, userTicket);
    }

    /**
     * 获取秒杀地址
     */
    // 接口限流
    @AccessLimit(second = 5, maxCount = 100)
    @GetMapping("/path")
    public RespBean getPath(String goodsId, @CookieValue String userTicket) {
        // 创建秒杀地址
        return secKillService.createPath(userTicket, goodsId);
    }

}
